package com.guet.task;

import com.guet.Entity.Paper;
import com.guet.Entity.Questions;
import com.guet.Entity.Score;
import com.guet.Entity.User;
import com.guet.context.BaseContext;
import com.guet.mapper.TestMapper;
import com.guet.service.TestService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class PaperTask {
    @Autowired
    private TestMapper testMapper;
    @Autowired
    private TestService testService;

    @Scheduled(cron = "0 * * * * ?") // 每分钟执行
    @Transactional
    public void changePaperStatus() {
        // 查询所有进行中的试卷
        List<Paper> papers = testMapper.queryAllPapers(1);

        for (Paper paper : papers) {
            if (paper.getStatus() == 1 && paper.getEndTime().isBefore(LocalDateTime.now())) {
                // 更新试卷状态
                testMapper.updateOverTimePaper(paper.getId());

                // 获取未作答用户
                List<Integer> notTestUserIds = testMapper.notTestUserIds(paper.getId());
                if (notTestUserIds != null && !notTestUserIds.isEmpty()) {
                    List<Score> scores = new ArrayList<>();
                    for (Integer userId : notTestUserIds) {
                        scores.add(Score.builder()
                                .userId(Long.valueOf(userId))
                                .paperId(paper.getId())
                                .score(0.0)
                                .build());
                    }
                    testMapper.insertBatchStuScores(scores);
                }
            }
        }
    }
}
